import React, { useState, useEffect } from 'react';
import { Form, Skeleton } from 'antd';
import { size } from 'lodash';
import { useRequest } from '@/hooks';
import { checkVerificationCode, resetForgetPassword } from '@/pages/EntryManage/services';
import { history } from 'umi'
import { InputItem, Toast } from 'antd-mobile';
import { FormItem, Button } from '@/pages/Recruitment/External/components/mobile';
import styles from '@/pages/Recruitment/External/components/mobile/FormItem.less';
import eye from '@/assets/entry/eye.png';
import eyeInvisible from '@/assets/entry/eye-invisible.png';
import cn from 'classnames';
import style from '../index.less';

// 设置新密码
const SetNewPassword = ({ form, email, name, verificationKey, verificationValue, setIsLinkTimeout, redirectId }) => {
    const { getFieldDecorator } = form;
    const [disabled, setDisabled] = useState(true);

    const [open, setOpen] = useState(false);
    const [open1, setOpen1] = useState(false);
    // 校验验证码是否过期
    const { loading: checkCodeLoading } = useRequest(
        () =>
            checkVerificationCode({
                type: 10,
                organizeType: 1,
                loginName: email,
                key: verificationKey,
                value: verificationValue
            }),
        {
            onSuccess: res => {
                if (res?.code !== 10000) {
                    setIsLinkTimeout(true);
                }
            }
        }
    );

    // 修改密码
    const { loading: resetPwdLoading, run: runResetPwd } = useRequest(params => resetForgetPassword(params), {
        manual: true
    });

    // 按钮是否disabled状态
    useEffect(() => {
        const values = form.getFieldsValue();
        const arr = Object.values(values).filter(item => !item || item === '');
        let hasError = false;
        Object.keys(values).forEach(item => {
            if (size(form.getFieldError(item)) > 0) {
                hasError = true;
            }
        });
        setDisabled(hasError || size(arr) > 0);
    }, [form]);

    const handleSubmit = () => {
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const payload = {
                    ...values,
                    verificationKey,
                    verificationValue,
                    loginName: email,
                    organizeType: 1
                };
                const { code, msg } = (await runResetPwd(payload)) || {};
                if (code === 10000) {
                    history.push({
                        pathname: '/external/interview/resetPassword',
                        query: { step: 4, name, id: redirectId }
                    });
                } else {
                    Toast.fail(msg);
                }
            }
        });
    };

    return (
        <Skeleton loading={checkCodeLoading}>
            <div className={cn(styles.resumeList, style.itemCtr)}>
                <FormItem label="密码" itemId="newPassword" form={form}>
                    {getFieldDecorator('newPassword', {
                        rules: [
                            {
                                required: false
                            },
                            {
                                validator(rule, value, callback) {
                                    const regex = /^(?:(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])).*$/;
                                    if (value) {
                                        const tempValue = value.trim();
                                        if (tempValue.length >= 8 && tempValue.length <= 20 && regex.test(value)) {
                                            const confirmNewPassword = form.getFieldValue('confirmNewPassword').trim();
                                            if (confirmNewPassword.length > 0) {
                                                if (tempValue !== confirmNewPassword) {
                                                    form.validateFields(['confirmNewPassword'], { force: true });
                                                } else {
                                                    form.validateFields(['confirmNewPassword'], { force: false });
                                                }
                                            }
                                            callback();
                                        } else {
                                            callback('长度为8-20个字符，需同时包含大小写字母及数字');
                                        }
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <InputItem
                            type={open ? 'text' : 'password'}
                            placeholder="密码"
                            className={cn(styles.inputI, style.password)}
                            clear
                            maxLength={20}
                        >
                            <div className={style.iconBtn} onClick={() => setOpen(!open)}>
                                <img alt="" src={open ? eye : eyeInvisible} width="10" height="10" />
                            </div>
                        </InputItem>
                    )}
                </FormItem>
                <FormItem label="确认密码" itemId="confirmNewPassword" form={form}>
                    {getFieldDecorator('confirmNewPassword', {
                        rules: [
                            {
                                required: false
                            },
                            {
                                validator(rule, value, callback) {
                                    if (value) {
                                        const tempValue = value.trim();
                                        const password = form.getFieldValue('newPassword').trim();
                                        if (tempValue === password) {
                                            callback();
                                        } else {
                                            callback('两次输入的密码不相同');
                                        }
                                    }
                                    callback();
                                }
                            }
                        ]
                    })(
                        <InputItem
                            type={open1 ? 'text' : 'password'}
                            placeholder="请输入确认密码"
                            className={cn(styles.inputI, style.password)}
                            clear
                            maxLength={20}
                        >
                            <div className={style.iconBtn} onClick={() => setOpen1(!open1)}>
                                <img alt="" src={open1 ? eye : eyeInvisible} width="10" height="10" />
                            </div>
                        </InputItem>
                    )}
                </FormItem>
                <Button
                    disabled={disabled}
                    loading={resetPwdLoading}
                    block
                    type="primary"
                    size="large"
                    onClick={handleSubmit}
                >
                    完成
                </Button>
            </div>
        </Skeleton>
    );
};

export default Form.create()(SetNewPassword);
